package com.zhaoyd.uaademo.config.security.integration.authenticator;

import com.zhaoyd.uaademo.config.security.MyUserDetail;
import com.zhaoyd.uaademo.config.security.integration.AbstractIntegrationAuthenticator;
import com.zhaoyd.uaademo.config.security.integration.IntegrationAuthentication;
import com.zhaoyd.uaademo.entity.SysUser;
import com.zhaoyd.uaademo.enums.LoginType;
import com.zhaoyd.uaademo.service.SysResourceService;
import com.zhaoyd.uaademo.service.SysRoleService;
import com.zhaoyd.uaademo.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

/**
 * 图形验证码登录
 * @author zhaoyd
 * @date 2020-11-08 22:49
 */
@Component
public class VerificationCodeIntegrationAuthenticator extends AbstractIntegrationAuthenticator {

    private final static String AUTH_TYPE = LoginType.VERIFICATION_CODE.name();

    private static final String USERNAME_PARM_NAME = "username";

    private static final String CODE_PARM_NAME = "code";

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysResourceService sysResourceService;
    @Override
    public boolean support(IntegrationAuthentication integrationAuthentication) {
        return StringUtils.equalsIgnoreCase(integrationAuthentication.getAuthType(), AUTH_TYPE);
    }

    @Override
    public void prepare(IntegrationAuthentication integrationAuthentication) {
        //不做操作
    }

    @Override
    public MyUserDetail authenticate(IntegrationAuthentication integrationAuthentication) throws AuthenticationException {
        String code = integrationAuthentication.getParameter(CODE_PARM_NAME);
        String username = integrationAuthentication.getParameter(USERNAME_PARM_NAME);
        if(StringUtils.isBlank(code)){
            throw new BadCredentialsException("验证码不能为空");
        }
        //校验验证码逻辑
        if(!StringUtils.equalsIgnoreCase("1234", code)){
            throw new BadCredentialsException("验证码不正确");
        }
        //查询用户
        SysUser sysUser = sysUserService.findByUsername(username);
        if(sysUser == null){
            //UsernameNotFoundException 会被会被BadCredentialsException("用户名或密码错误")覆盖掉
            throw new UsernameNotFoundException(username);
        }
        Set<String> roleCodes = sysRoleService.listRoleCodeByUser(sysUser.getId());
        Set<String> resourceCodes = sysResourceService.listResourceCodeByUser(sysUser.getId());
        return MyUserDetail.build(sysUser, roleCodes, resourceCodes);
    }

    @Override
    public void complete(IntegrationAuthentication integrationAuthentication) {

    }
}
